import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;



public class Fen extends JFrame {

	private Content content;
	private int time = 600;
	private Thread thread;
	public Fen()
	{
		super();

		content = new Content(new Grid(9,20));
		this.setTitle("Tetris");
		this.setSize(480, 672);
		this.setLocationRelativeTo(null);               
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setContentPane(content);
		this.setResizable(false);
		this.setVisible(true);
		this.addKeyListener(new ClavierListener());
	}





	class ClavierListener implements KeyListener
	{
	

		// Implémentation de l'interface de KeyListener

		public  void keyPressed(KeyEvent e)
		{
			char key = e.getKeyChar();
			if (content.is_end)
			{
				switch (key)
				{
					case '\n':
						content.setGrid( new Grid(9,20));
						content.reinit();	
						break;
					case 'q':
						System.exit(0);
						break;
				}
			}

			else if (content.is_pause)
			{
				if (key == 'p')
				{
					content.is_pause = false;
					content.repaint();
					thread = new Thread(new MyThread());
					thread.start();
				}
			}

			else if (content.is_start)
			{
				if (key == '\n')
				{
					content.is_start = false;
					content.repaint();

					thread = new Thread(new MyThread());
					thread.start();
				}
			}

			else if (!content.is_pause && key == 'p')
			{
				content.is_pause = true;
				content.repaint();
			}

			else 
			{
				switch (e.getKeyCode())
				{
					case 37: // Flèche gauche
						content.moveLeft();
						break;

					case 38: // Flèche haut
						content.rotate();
						break;
					case 39: // flèche droite
						content.moveRight();
						break;

					case 40: // Flèche bas
						content.moveDown();
						break;
				}
			}			
			
		}

		public void keyReleased(KeyEvent e)
		{
		}

		public void keyTyped(KeyEvent e)
		{
		}

	}
	
	public void maj_timer()
	{
		time = 3500/(5+content.level) ;
	}

	class MyThread implements Runnable
	{

		public void run()
		{
			while (!content.is_pause && !content.is_end)
			{
				maj_timer();
				try{
					Thread.sleep(time);
					
				}
				catch (InterruptedException e)
				{
					e.printStackTrace();
				}
				if (!content.is_pause)
					content.moveDown();
				
			}
		}

	}

}
